<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/12 0012
 * Time: 18:50
 */

namespace common\models\AgentPlugs;


use common\components\GlobalUrlComponent;
use common\models\Plug\Plug;

class AgentPlugs extends AgentPlugsBase
{
    public static function generateJsonFile($agentId)
    {
        $ret = self::find()->where([
            "agent_uid" => $agentId
        ])->asArray()->all();
        if ( !$ret ) {
            return true;
        }
        $plugsId = array_column($ret, "plug_id");
        $plugs = Plug::find()->where([
            "id" => $plugsId,
            "status" => Plug::STATUS_YES
        ])->asArray()->all();
        if ( !$plugs ) {
            return true;
        }

        foreach ( $plugs as &$item ) {
            $item["aero"] = $item["area"];
            $item["time"] = $item["start_delayed"];
            //$item["bk"] = $item["valid_time"];
            #$item["md5"] = md5($item["url"]);
            unset($item["area"], $item["start_delayed"], $item["created_time"], $item["updated_time"], $item["status"]);
        }
        $plugs = json_encode($plugs);
        $filename = $agentId . ".json";
        $dir = \Yii::getAlias("@static");
        $filename = $dir . DIRECTORY_SEPARATOR . "web".DIRECTORY_SEPARATOR."agent_plugs_json" . DIRECTORY_SEPARATOR . $filename;
        if ( file_put_contents($filename, $plugs) ) {
            return true;
        }
        return false;
    }

    public static function getJsonFileUrl($agentId)
    {
        return GlobalUrlComponent::buildStaticUrl("/agent_plugs_json/" . $agentId . ".json");
    }


}